package com.alibaba.serverless;

import com.alibaba.serverless.common.ApiGwRequest;
import com.alibaba.serverless.common.ApiGwResponse;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.FunctionComputeLogger;
import com.aliyun.fc.runtime.FunctionInitializer;
import com.aliyun.fc.runtime.PojoRequestHandler;
import com.aliyuncs.utils.Base64Helper;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class NasFileHandler implements FunctionInitializer, PojoRequestHandler<ApiGwRequest, ApiGwResponse> {

	/*
	 * 云函数初始化
	 * 
	 * @see com.aliyun.fc.runtime.FunctionInitializer#initialize(com.aliyun.fc.
	 * runtime.Context)
	 */
	@Override
	public void initialize(Context context) {
		FunctionComputeLogger logger = context.getLogger();
		logger.debug(String.format("RequestID is %s %n", context.getRequestId()));
	}

	/*
	 * Web云函数处理入口
	 * 
	 * @see com.aliyun.fc.runtime.PojoRequestHandler#handleRequest(java.lang.Object,
	 * com.aliyun.fc.runtime.Context)
	 */
	@Override
	public ApiGwResponse handleRequest(ApiGwRequest request, Context context) {
		FunctionComputeLogger logger = context.getLogger();
		// 测试访问外网
		StringBuilder sb = new StringBuilder();
		writeFile( sb );
		readFile( sb );
		String bodyContext = "<html>" + sb.toString()  + "</html>";

		ApiGwResponse response = new ApiGwResponse();
		response.getHeaders().put("responseHeader", "testValue");
		response.getHeaders().put("Content-type", "text/html; charset=utf-8");
		// boolean isBase = request.getIsBase64Encoded();
		boolean isBase = false;
		// 响应内容是JSON，不用编码, 建议和 request内部编码保持一致
		if (isBase) {
			try {
				bodyContext = Base64Helper.encode(bodyContext, "UTF-8");
			} catch (UnsupportedEncodingException e) { // 编码失败，就用原文
				isBase = false;
			}
		}

		logger.info("Response返回:" + bodyContext);

		response.setBody(bodyContext);
		response.setBase64Encoded(isBase);
		response.setStatusCode(200);

		return response;

	}
	
	private void writeFile( StringBuilder  sb ) {
		String nasPath = System.getenv("workbench_nas_path");
		if( nasPath==null  ) {
			nasPath = System.getProperty("workbench_nas_path");
			if( nasPath==null  ) {
				sb.append( "NAS本地路径不存在环境配置: workbench_nas_path " ).append("<br>");
				nasPath = "/mnt/auto";
			}
		}
		sb.append( "NAS本地路径: workbench_nas_path =" + nasPath ).append("<br>");
		try {
			File filePath = new File( nasPath );
			if (filePath.exists()) {
				sb.append( "reWriteFile NAS本地路径: " + nasPath ).append("，存在！").append("<br>");
				// 创建文件
				String newFileName = filePath.getPath() + "/abc.txt";
				// 打开一个随机访问文件流，按读写方式   
	            RandomAccessFile randomFile = new RandomAccessFile( newFileName, "rw");   
	            // 文件长度，字节数   
	            long fileLength = randomFile.length();   
	            sb.append( "当前文件长度：" +  fileLength ).append("<br>");
	            // 将写文件指针移到文件尾。   
	            randomFile.seek(fileLength);   
	            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	            String strTime = df.format( Calendar.getInstance().getTime() );
	            randomFile.write( ( strTime + "函数计算服务写入！").getBytes("UTF-8") );   
	            randomFile.close();   
			} else {
				sb.append( "NAS本地路径: 不存在" ).append("<br>");
			}
		} catch (Exception e) {
			sb.append( "发生异常：" + ex2String(e) ).append("<br>");
		}
	}
	
	private void readFile( StringBuilder  sb ) {
		String nasPath = System.getenv("workbench_nas_path");
		if( nasPath==null  ) {
			nasPath = System.getProperty("workbench_nas_path");
			if( nasPath==null  ) {
				sb.append( "NAS本地路径不存在环境配置: workbench_nas_path " ).append("<br>");
				nasPath = "/mnt/auto";
			}
		}
		sb.append( "NAS本地路径: workbench_nas_path =" + nasPath ).append("<br>");
		try {
			File filePath = new File( nasPath );
			// 创建文件
			String newFileName = filePath.getPath() + "/abc.txt";
			// 打开一个随机访问文件流，按读写方式   
	        RandomAccessFile randomFile = new RandomAccessFile( newFileName, "rw");   
	        long fileLength = randomFile.length();   
	        while( randomFile.getFilePointer()<fileLength ) {
	        	sb.append( new String( randomFile.readLine().getBytes("ISO8859_1"), "UTF-8" )).append("<br>");
	        }
	        randomFile.close();   
		} catch (Exception e) {
			sb.append( "读文件发生异常：" + ex2String(e) ).append("<br>");
		}
	}
	
	
	private String ex2String(Exception t) {
		StringWriter sw = new StringWriter();
		t.printStackTrace(new PrintWriter(sw, true));
		return sw.getBuffer().toString();
	}

}
